import _ from 'lodash'

import { getGlobalState } from '@/globalStore/globalStore'

const getHideKey = (id: number) => `fba_${$APP}_${id}_TrackOrder_List_colHideFlags`
const getExtKey = (id: number) => `fba_${$APP}_${id}_TrackOrder_List_colExtFlags`

export const getColHideFlags = (): Record<string, boolean | undefined> => {
  const id = getGlobalState().userInfo?.id
  if (id) {
    const valStr = localStorage.getItem(getHideKey(id))
    if (valStr) {
      try {
        return JSON.parse(valStr)
      } catch (err) {
        console.error(err)
      }
    }
  }
  return {}
}
export const setColHideFlags = (partialFlags: Record<string, boolean | undefined>) => {
  const id = getGlobalState().userInfo?.id
  if (id) {
    const oldFlags = getColHideFlags()
    const newFlags = { ...oldFlags, ...partialFlags }
    try {
      const valStr = JSON.stringify(_.pickBy(newFlags, v => v === true))
      localStorage.setItem(getHideKey(id), valStr)
    } catch (err) {
      console.error(err)
    }
  }
}

export const getColExtFlags = (): { [groupId: string]: boolean | undefined } => {
  const id = getGlobalState().userInfo?.id
  if (id) {
    const valStr = localStorage.getItem(getExtKey(id))
    if (valStr) {
      try {
        return JSON.parse(valStr)
      } catch (err) {
        console.error(err)
      }
    }
  }
  return {}
}
export const setColExtFlags = (groupId: string, value: boolean) => {
  const id = getGlobalState().userInfo?.id
  if (id) {
    const oldFlags = getColExtFlags()
    const newFlags = { ...oldFlags, [groupId]: value }
    try {
      const valStr = JSON.stringify(_.pickBy(newFlags, v => v === true))
      localStorage.setItem(getExtKey(id), valStr)
    } catch (err) {
      console.error(err)
    }
  }
}
